package com.store.controller;

import com.store.common.Result;
import com.store.dto.OrderDTO;
import com.store.entity.Order;
import com.store.mapper.OrderMapper;
import com.store.service.OrderService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/orders")
public class OrderController {

    @Autowired
    private OrderService orderService;
    
    @Autowired
    private OrderMapper orderMapper;

    @GetMapping
    public Result list(
            @RequestParam(required = false) Integer pageNum, 
            @RequestParam(required = false) Integer pageSize,
            @RequestParam(required = false) String orderNo,
            @RequestParam(required = false) String status) {
        
        System.out.println("接收到订单查询请求: pageNum=" + pageNum + ", pageSize=" + pageSize + 
                          ", orderNo=" + orderNo + ", status=" + status);
        
        // 构建查询条件
        if (pageNum != null && pageSize != null) {
            // 分页查询
            List<OrderDTO> orderDTOs = orderService.getAllOrders();
            
            // 根据条件过滤
            if ((orderNo != null && !orderNo.isEmpty()) || (status != null && !status.isEmpty())) {
                orderDTOs = orderDTOs.stream()
                    .filter(order -> {
                        boolean match = true;
                        
                        // 按订单号筛选
                        if (orderNo != null && !orderNo.isEmpty()) {
                            match = match && order.getOrderNo().contains(orderNo);
                        }
                        
                        // 按状态筛选
                        if (status != null && !status.isEmpty()) {
                            match = match && status.equals(order.getStatus());
                        }
                        
                        return match;
                    })
                    .collect(java.util.stream.Collectors.toList());
            }
            
            // 计算总数
            int total = orderDTOs.size();
            
            // 分页
            int start = (pageNum - 1) * pageSize;
            int end = Math.min(start + pageSize, orderDTOs.size());
            
            if (start < orderDTOs.size()) {
                orderDTOs = orderDTOs.subList(start, end);
            } else {
                orderDTOs = new java.util.ArrayList<>();
            }
            
            // 构建分页结果
            java.util.Map<String, Object> result = new java.util.HashMap<>();
            result.put("records", orderDTOs);
            result.put("total", total);
            
            return Result.success(result);
        } else {
            // 不分页，返回所有订单
            List<OrderDTO> orderDTOs = orderService.getAllOrders();
            
            // 根据条件过滤
            if ((orderNo != null && !orderNo.isEmpty()) || (status != null && !status.isEmpty())) {
                orderDTOs = orderDTOs.stream()
                    .filter(order -> {
                        boolean match = true;
                        
                        // 按订单号筛选
                        if (orderNo != null && !orderNo.isEmpty()) {
                            match = match && order.getOrderNo().contains(orderNo);
                        }
                        
                        // 按状态筛选
                        if (status != null && !status.isEmpty()) {
                            match = match && status.equals(order.getStatus());
                        }
                        
                        return match;
                    })
                    .collect(java.util.stream.Collectors.toList());
            }
            
            return Result.success(orderDTOs);
        }
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Long id) {
        return Result.success(orderService.getOrderById(id));
    }

    @PostMapping
    public Result create(@RequestBody OrderDTO orderDTO) {
        return Result.success(orderService.createOrder(orderDTO));
    }

    @PutMapping
    public Result update(@RequestBody OrderDTO orderDTO) {
        return Result.success(orderService.updateOrder(orderDTO));
    }

    @DeleteMapping("/{ids}")
    public Result<?> delete(@PathVariable List<Long> ids) {
        orderService.deleteOrders(ids);
        return Result.success();
    }

    @PutMapping("/{id}/quantity")
    public Result updateQuantity(
            @PathVariable Long id,
            @RequestBody UpdateQuantityRequest request) {
        return Result.success(orderService.updateOrderQuantity(id, request.getQuantity()));
    }

    /**
     * 支付订单
     * @param id 订单ID
     * @return 支付结果
     */
    @PostMapping("/{id}/pay")
    public Result payOrder(@PathVariable Long id) {
        // 验证订单状态并更新为已支付
        Order order = orderMapper.selectById(id);
        if (order == null) {
            return Result.error(404, "订单不存在");
        }
        if (!"PENDING".equals(order.getStatus())) {
            return Result.error(400, "该订单不是待付款状态");
        }
        
        orderService.updateStatus(id, "PAID");
        return Result.success();
    }

    /**
     * 更新订单发货状态
     * @param id 订单ID
     * @param request 发货状态请求
     * @return 更新结果
     */
    @PutMapping("/{id}/shipping-status")
    public Result updateShippingStatus(@PathVariable Long id, @RequestBody UpdateShippingStatusRequest request) {
        // 验证订单状态
        Order order = orderMapper.selectById(id);
        if (order == null) {
            return Result.error(404, "订单不存在");
        }
        
        // 验证当前订单是否为已付款状态
        if (!"PAID".equals(order.getStatus())) {
            return Result.error(400, "只有已付款的订单才能更新发货状态");
        }
        
        // 验证目标状态是否合法
        String newStatus = request.getStatus();
        if (!isValidShippingStatus(newStatus)) {
            return Result.error(400, "无效的发货状态");
        }
        
        // 更新订单状态
        orderService.updateStatus(id, newStatus);
        return Result.success();
    }
    
    /**
     * 验证发货状态是否合法
     */
    private boolean isValidShippingStatus(String status) {
        return "SHIPPED".equals(status);
    }

    /**
     * 取消订单
     * @param id 订单ID
     * @return 取消结果
     */
    @PostMapping("/{id}/cancel")
    public Result cancelOrder(@PathVariable Long id) {
        // 验证订单是否存在
        Order order = orderMapper.selectById(id);
        if (order == null) {
            return Result.error(404, "订单不存在");
        }
        
        // 验证订单状态是否为待付款
        if (!"PENDING".equals(order.getStatus())) {
            return Result.error(400, "只有待付款状态的订单才能取消");
        }
        
        // 更新订单状态为已取消
        orderService.updateStatus(id, "CANCELLED");
        return Result.success();
    }
    
    /**
     * 完成订单
     * @param id 订单ID
     * @return 完成结果
     */
    @PostMapping("/{id}/complete")
    public Result completeOrder(@PathVariable Long id) {
        // 验证订单是否存在
        Order order = orderMapper.selectById(id);
        if (order == null) {
            return Result.error(404, "订单不存在");
        }
        
        // 验证订单状态是否为已发货
        if (!"SHIPPED".equals(order.getStatus())) {
            return Result.error(400, "只有已发货状态的订单才能标记为已完成");
        }
        
        // 更新订单状态为已完成
        orderService.updateStatus(id, "COMPLETED");
        return Result.success();
    }
    
    /**
     * 创建测试订单（待付款状态）
     * @return 创建结果
     */
    @PostMapping("/test")
    public Result createTestOrder() {
        OrderDTO orderDTO = new OrderDTO();
        orderDTO.setOrderNo("TEST" + System.currentTimeMillis());
        orderDTO.setStatus("PENDING"); // 设置为待付款状态
        orderDTO.setTotalAmount(new java.math.BigDecimal("99.99"));
        orderDTO.setQuantity(1);
        orderDTO.setShippingName("测试用户");
        orderDTO.setShippingPhone("13800138000");
        orderDTO.setShippingAddress("测试地址");
        orderDTO.setProductName("测试商品");
        orderDTO.setProductPrice(new java.math.BigDecimal("99.99"));
        
        return Result.success(orderService.createOrder(orderDTO));
    }
}

@Data
class UpdateQuantityRequest {
    private Integer quantity;  // 新的购买数量
}

/**
 * 更新发货状态请求
 */
@Data
class UpdateShippingStatusRequest {
    private String status;  // 新的发货状态：SHIPPED-已发货
} 